//jqGrid的配置信息
$.jgrid.defaults.width = 1000;
$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

//工具集合Tools
window.T = {};

// 获取请求参数
// 使用示例
// location.href = http://localhost:8080/index.html?id=123
// T.p('id') --> 123;
var url = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        if(r[2] != null &&!(r[2].indexOf( "%" )<0)) {
           return r[2] = decodeURI(r[2]);
        }
        return  unescape(r[2]);
    } else {
        return null;
    }
};
T.p = url;


var dictItem = function (groupCode) {
    var resData = null;
    $.ajax({
        type: "get",
        url: "/dictItem/getDictItemByGroupCode",
        data: {"groupCode": groupCode},
        async: false,
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                resData = data.resData;
            }
        }
    });
    return resData;
};
T.getDictItems = dictItem;

var showDictItemName = function (groupCode, dictCode) {
    var resData = null;
    $.ajax({
        type: "post",
        url: "/dictItem/showDictItem",
        data: {"groupCode": groupCode, "dictCode": dictCode},
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        async: false,
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                resData = data.resData;
            }
        }
    });
    if (resData) {
        if (resData.dictName) {
            var str = "";
            if (resData.cssClass || resData.cssStyle) {
                str += "<span";
                if (resData.cssClass) {
                    str += ' class="' + resData.cssClass + '"'
                }
                if (resData.cssStyle) {
                    str += ' style="' + resData.cssStyle + '"'
                }
                return str + ">" + resData.dictName + "</span>";
            }

            return resData.dictName;
        }

    }
    return "";
};
T.showDictItemName = showDictItemName;


var dictDyna = function (groupCode,params) {
    var resData = null;
    $.ajax({
        type: "get",
        url: "/dictDyna/getDictDynaByGroupCode",
        data: {"groupCode": groupCode,"params":JSON.stringify(params)},
        async: false,
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                resData = data.resData;
            }
        }
    });
    return resData;
};
T.getDictDynas = dictDyna;

var showDictDynaName = function (groupCode, dictCode) {
    var dicts = T.getDictDynas(groupCode);
    var rtValue = "";
    dicts.some(function (value) {
        if (value.dictCode) {
            if (value.dictCode == dictCode) {
                if (value.dictName) {
                    rtValue = value.dictName;
                    return;
                }
            }
        }
    });
    return rtValue;
};
T.showDictDynaName = showDictDynaName;

//全局配置
$.ajaxSetup({
    dataType: "json",
    contentType: "application/json",
    cache: false
});

//重写alert
window.alert = function (msg, callback) {
    top.layer.alert(msg, function (index) {
        top.layer.close(index);
        if (typeof(callback) === "function") {
            callback("ok");
        }
    });
}

//重写confirm式样框
window.confirm = function (msg, callback) {
    top.layer.confirm(msg, {btn: ['确定', '取消']},
        function (index) {//确定事件
            top.layer.close(index);
            if (typeof(callback) === "function") {
                callback("ok");
            }
        });
}

//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        alert("请选择一条记录");
        return;
    }

    var selectedIDs = grid.getGridParam("selarrrow");
    if (selectedIDs.length > 1) {
        alert("只能选择一条记录");
        return;
    }
    if (!selectedIDs.length || selectedIDs.length == 0) {
        return rowKey;
    }

    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows(alertFlag) {
    if (alertFlag == 'undefined') {
        alertFlag = true;
    }
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey && alertFlag) {
        alert("请选择一条记录");
        return;
    }

    return grid.getGridParam("selarrrow");
}


//优化jqgrid
var btnMoreEventBind = function (gridName) {
    if (gridName == 'undefined'||null == gridName) {
        gridName = "jqGrid";
    }
    $("td[aria-describedby='jqGrid_actions']").addClass("actions");
    var dataGrid = $("#"+gridName);
    var elements = dataGrid.find(".btnMore");
    dataGrid.find(".moreItems").hide();
    elements.each(function () {
        if ($(this).attr("data-mouseover-binded") == undefined) {
            $(this).attr("data-mouseover-binded", true);
            var timeoutHover;
            elements.mouseover(function () {
                var bdiv = dataGrid.closest(".ui-jqgrid-bdiv"), more = $(this), items = more.next(),
                    pos = more.position(), top = pos.top - items.height() / 2 + 6,
                    left = pos.left - items.width() - 2;
                if (!items.hasClass("moreItems")) {
                    return
                }
                dataGrid.find(".btnMore.open").removeClass("open").find("i").removeClass("fa-chevron-circle-left").addClass("fa-chevron-circle-right");
                dataGrid.find(".moreItems.open").removeClass("open").hide();
                var itemsTop = bdiv.scrollTop() + 5;
                if (top <= itemsTop) {
                    top = itemsTop
                } else {
                    itemsTop = bdiv.height() - items.height() + itemsTop - 12;
                    if (top >= itemsTop) {
                        top = itemsTop
                    }
                }
                more.addClass("open").find("i").removeClass("fa-chevron-circle-right").addClass("fa-chevron-circle-left");
                items.addClass("open").css({top: top, left: left}).show();
                if (items.attr("data-hover-binded") == undefined) {
                    items.attr("data-hover-binded", true);
                    items.hover(function () {
                        window.clearTimeout(timeoutHover)
                    }, function () {
                        window.clearTimeout(timeoutHover);
                        timeoutHover = window.setTimeout(function () {
                            more.removeClass("open").find("i").removeClass("fa-chevron-circle-left").addClass("fa-chevron-circle-right");
                            items.hide()
                        }, 500)
                    }).find("a").click(function () {
                        more.removeClass("open").find("i").removeClass("fa-chevron-circle-left").addClass("fa-chevron-circle-right");
                        items.hide()
                    })
                }
            })
        }
    });

    var btnElms = dataGrid.find(".btnList");

    btnElms.each(function () {
        if ($(this).attr("data-click-binded") == undefined) {
            $(this).attr("data-click-binded", true);
            $(this).click(function () {
                var se = $(this);
                var clickMth = se.data("click");
                var confirmMsg = se.data("confirm");
                if (confirmMsg != undefined && clickMth != undefined) {
                    confirm(confirmMsg, function () {
                        eval(clickMth)
                    });
                }
                return false
            })
        }
    });
}

//获取当前表格的所有数据
var getJQAllData = function (gridName) {
    if (gridName == 'undefined'||null == gridName) {
        gridName = "jqGrid";
    }
    //拿到grid对象
    var obj = $("#"+gridName);
//获取grid表中所有的rowid值
    var rowIds = obj.getDataIDs();
//初始化一个数组arrayData容器，用来存放rowData
    var arrayData = new Array();
    if (rowIds.length > 0) {
        for (var i = 0; i < rowIds.length; i++) {
            //rowData=obj.getRowData(rowid);//这里rowid=rowIds[i];
            arrayData.push(obj.getRowData(rowIds[i]));
        }
    }
    return arrayData;
}


/**************************************时间格式化处理************************************/
function dateFtt(fmt,date)
{ //author: meizz
    var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}
